from tool import custom_round

def precompute_steps(table_size=1000):
    step_table = {}
    for i in range(-table_size, table_size + 1):
        # 计算斜率
        slope = i / table_size
        # 斜率小于或等于1，x每步增加1
        # 斜率大于1，y每步增加1
        x_per_step, y_per_step = (1, slope) if abs(slope) <= 1 else (1 / abs(slope), 1 if slope > 0 else -1)
        step_table[slope] = (x_per_step, y_per_step) # 打表
    return step_table

def DDADrawLine(x1, y1, x2, y2, optimize=False, step_table=None):
    dot_list = []
    dx = x2 - x1
    dy = y2 - y1
    
    if optimize and step_table is not None:
        # 如果步进表中已存在该斜率，直接使用预先计算的步幅
        slope = dy / dx if dx != 0 else float('inf')
        if slope in step_table:
            x_per_step, y_per_step = step_table[slope]
            steps = max(abs(dx), abs(dy))
        else:
            # 否则，按常规方法计算步幅
            steps = max(abs(dx), abs(dy))
            x_per_step = dx / steps
            y_per_step = dy / steps
    else:
        # 未启用优化
        steps = max(abs(dx), abs(dy))
        x_per_step = dx / steps
        y_per_step = dy / steps

    x_draw, y_draw = x1, y1

    for i in range(steps):
        print(x_draw, y_draw)
        # dot_list.append((round(x_draw), round(y_draw)))
        #  自定义舍入函数
        dot_list.append((custom_round(x_draw), custom_round(y_draw)))
        x_draw += x_per_step
        y_draw += y_per_step

    # 最后一个点添加进去

    dot_list.append((x2, y2))
    
    return dot_list
